package com.ervanalb.cellradio.shared;

import java.util.LinkedList;
import java.util.List;


/**
 * Wraps a type with callback methods. Used for maintaining state as well as
 * event-based programming without the need for polling. When set is called on a
 * ControlObject, it notifies all of its UpdateListeners. Note that this is done
 * synchronously, so UpdateListeners should be fast.
 * 
 * @author eric
 * @param <E>
 *            the wrapped type.
 */
public class ControlObject<E> {
	protected E value;
	protected List<UpdateListener<E>> listeners;

	public ControlObject(E init) {
		synchronized (this) {
			value = init;
			listeners = new LinkedList<UpdateListener<E>>();
		}
	}

	public void set(E newValue) {
		synchronized (this) {
			value = newValue;
			for (UpdateListener<E> l : listeners) {
				l.update(this);
			}
		}
	}

	public E get() {
		synchronized (this) {
			return value;
		}
	}
}
